package com.cai.oamanager.controller;

import com.cai.oamanager.entity.PageUtil;
import com.cai.oamanager.entity.People;
import com.cai.oamanager.entity.SendFile;
import com.cai.oamanager.service.SendFileService;
import com.cai.oamanager.service.UserService;
import com.cai.oamanager.utils.Uploadpath;
import com.cai.oamanager.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.Inet4Address;
import java.net.URLEncoder;
import java.util.List;

/**
 * @version 1.0
 * @author：蔡松坡
 * @date：2021/1/22 10 : 45
 * @package：com.cai.oamanager.controller
 */
@Controller
@RequestMapping("file")
public class FileController {

    @Autowired
    private SendFileService sendFileService;

    @Autowired
    private UserService userService;

    /**
     * 发送文件列表显示
     * @param request
     * @param model
     * @param liketext
     * @param currentPage
     * @return
     */
    @RequestMapping("sendfile.html")
    public String getAllSendFiles(HttpServletRequest request, Model model,@RequestParam(defaultValue = "") String liketext, @RequestParam(defaultValue = "1") Integer currentPage){
        People people = (People) request.getSession().getAttribute("people");
        String oid = people.getOid();
        int count = sendFileService.getSendFileCount(oid);
        PageUtil pageUtil = new PageUtil();
        pageUtil.setSize(5);
        pageUtil.setCurrentPage(currentPage);
        pageUtil.setTotal(count);
        pageUtil.startPage();
        pageUtil.totalNumPage();
        List<SendFile> fileList = sendFileService.getAllSendFiles(oid, liketext, pageUtil.getStart(), pageUtil.getSize());
        model.addAttribute("fileList",fileList);
        model.addAttribute("pageUtil",pageUtil);
        model.addAttribute("liketext",liketext);
        return "sendfile";
    }

    /**
     * 跳转到上传页面
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("toUpFile")
    public String toUpFile(HttpServletRequest request,Model model){
        People people = (People) request.getSession().getAttribute("people");
        List<People> teacherName = userService.getTeacherName(people.getOid());
        model.addAttribute("teacherName",teacherName);
        return "upfile";
    }

    /**
     * 删除文件
     * @param fsid
     * @return
     */
    @RequestMapping("delete/{fsid}")
    public String deleteFile(@PathVariable("fsid") Integer fsid){
        sendFileService.deleteFile(fsid);
        return "redirect:/file/sendfile.html";
    }

    /**
     * 上传文件
     * @param request
     * @param model
     * @param mfile
     * @param sendFile
     * @return
     */
    @RequestMapping("upFile")
    public String upFile(HttpServletRequest request,Model model,MultipartFile mfile,SendFile sendFile){
        if(!mfile.isEmpty()){
            System.out.println("mfile>>> "+mfile);
            People people = (People) request.getSession().getAttribute("people");
            sendFile.setFspid(people.getOid());
            sendFile.setFspname(people.getOname());
            String filename = mfile.getOriginalFilename();
            if(filename.length()>50){
                return "redirect:/file/toUpFile";
            }
            String path = Uploadpath.getUpFilePath();
            sendFile.setFtime(Utils.getDate());
            if(sendFile.getFstype().equals("群发")){
                sendFile.setFcount(0);
            }else if(sendFile.getFstype().equals("私发")){
                sendFile.setFstate(0);
            }
            try {
                sendFile.setFname(filename);
                mfile.transferTo(new File(path,filename));
            } catch (IOException e) {
                e.printStackTrace();
            }
            sendFileService.addSendFile(sendFile);
            return "redirect:/file/sendfile.html";
        }
        model.addAttribute("msg","上传失败");
        return "redirect:/file/toUpFile";
    }

    /**
     *接收文件显示
     * @param model
     * @param request
     * @param liketext
     * @param currentPage
     * @return
     */
    @RequestMapping("reciveFile")
    public String reciveFile(Model model,HttpServletRequest request,@RequestParam(defaultValue = "") String liketext,@RequestParam(defaultValue = "1") Integer currentPage){
        People people = (People) request.getSession().getAttribute("people");
        String oid = people.getOid();
        Integer oposition = people.getOposition();
        int count = sendFileService.getReciveFileCount(oid, oposition);
        PageUtil pageUtil = new PageUtil();
        pageUtil.setSize(5);
        pageUtil.setCurrentPage(currentPage);
        pageUtil.setTotal(count);
        pageUtil.totalNumPage();
        pageUtil.startPage();
        List<SendFile> reciveFilesList = sendFileService.getAllReciveFiles(oid, oposition, liketext, pageUtil.getStart(), pageUtil.getSize());
        model.addAttribute("reciveFilesList",reciveFilesList);
        model.addAttribute("pageUtil",pageUtil);
        model.addAttribute("liketext",liketext);
        return "recivefile";
    }

    /**
     * 文件下载
     */
    @RequestMapping("download/{filename}/{fsid}/{fstype}")
    public String fileDownload(HttpServletResponse response,Model model,@PathVariable("filename") String filename,@PathVariable("fsid") Integer fsid,@PathVariable("fstype") Integer fstype) throws UnsupportedEncodingException {
        if(fstype==0){//私发
            sendFileService.updateState(fsid);
        }else if(fstype==1){
            int count = sendFileService.getCount(fsid);
            count++;
            System.out.println(fsid+" <<>> "+count);
            sendFileService.updateCount(count,fsid);
        }
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setContentType("application/force-download");
        System.out.println("filename>>"+filename);
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
        byte[] buff = new byte[1024];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();

            String path = Uploadpath.getUpFilePath();
            //这个路径为待下载文件的路径
            bis = new BufferedInputStream(new FileInputStream(new File(path + File.separator + filename )));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch ( IOException e ) {
            e.printStackTrace();
            //出现异常返回给页面失败的信息
            model.addAttribute("result","下载失败");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "redirect:/file/reciveFile";
    }

}
